import axios, { AxiosInstance } from 'axios'
import qs from 'qs';
import Aes from './aes';

import { getCookie, getToken } from './utils';

const flag = process.env.NODE_ENV == 'development' || location.host === 'dev.meix.com' || location.host === 'demo.meix.com';
const enabled = flag ? 0 : 1;
const userAgent = window.navigator.userAgent
  .substr(window.navigator.userAgent.lastIndexOf(')') + 2)
  .split(' ')[0];
const { encrypt } = Aes

const baseHeader = {
  appVersion: '3.5.0',
  enabled,
  curPageCode: 'P1',
  prevPageCode: 'P1',
  clientType: 9,
  deviceType: 3,
  loginType:1,
  uuid: getCookie('pcToken'),
  browserVersion: userAgent,
  ContentType: 'multipart/form-data'
};

const service: AxiosInstance = axios.create({
  headers: baseHeader,
  timeout: 6 * 1000
})

const post = (url, data) => {
  return service.post(url, qs.stringify(data));
};

const get = (url) => {
  return service.get(url);
};

const commomReq = (url, params) => {
  const paramsData = {
    ...params,
    'token': getToken()
  };
  const data = {
    'clientstr': baseHeader.enabled != 1 ? JSON.stringify(paramsData) : encrypt(paramsData),
    'oldUrlFix': baseHeader.enabled != 1 ? url : encrypt(url),
    'enabled': baseHeader.enabled
  };
  return post('/iaweb/forword/all', data);
};

const iawebReq = (url, params) => {
  const paramsData = {
    ...params,
    'token': getToken()
  };
  console.info('%c请求参数', 'color:green;font-weight:bold;');
  console.info(paramsData, 'color:green;font-weight:bold;');
  const data = {
    'clientstr': Aes.encrypt(paramsData),
    'oldUrlFix': '',
    'enabled': 1
  };
  return post(url, data);
};

service.interceptors.response.use(
  response => {
    let { data } = response;
    if (data) {
      let temp = null;
      temp = data;
      try {
        data = JSON.parse(Aes.decrypt(response.data.replace(/"/g, '')));
      } catch (e) {
      }
    }
    return data;
  },
  error => {
    return Promise.reject(error);
  }
);

export {
  post,
  get,
  commomReq,
  iawebReq
}
